package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.To.SkuHasStockVo;
import com.atguigu.common.To.mq.OrderTo;
import com.atguigu.common.To.mq.StockDeailTo;
import com.atguigu.common.To.mq.StockLockedTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.exception.NoStockException;
import com.atguigu.gulimall.ware.feign.OrderFeign;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderEntityVo;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.WareStockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.core.ChannelCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    WareOrderTaskService orderTaskService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderFeign orderFeign;


    /**
     * 解锁库存
     * @param skuId
     * @param wareId
     * @param skuNum
     */
    private void unStockLock(Long skuId, Long wareId, Integer skuNum,Long TaskId) {
        this.baseMapper.unStockLock(skuId,wareId,skuNum); //跟新库存信息
        //跟新工作单信息
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(TaskId);
        detailEntity.setLockStatus(2);//已解锁
        orderTaskDetailService.updateById(detailEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("skuId");
        if (!StringUtils.isEmpty(key)){
            wrapper.eq("sku_id",key);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 根据skuid查询库存是否为空
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> findSkuStock(List<Long> skuIds) {
        //遍历商品id判断是否有库存
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            Long count = this.baseMapper.selectBySkuIds(skuId);
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            //如果count==null则没有库存 大于0则存在库存
            skuHasStockVo.setHasStock(count==null?false:count>0);
            skuHasStockVo.setSkuId(skuId);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 锁库存
     * @param vo
     * @return
     */

    @Override
    public Boolean wareStock(WareStockVo vo) {
        //保存工作单
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);

        //找到每个商品在有几个仓库
        List<OrderItemVo> orderItemVos = vo.getOrderItemVos();//获取商品信息

        List<SkuWareHasStock> collect = orderItemVos.stream().map(item -> {
            SkuWareHasStock hasStock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            hasStock.setSkuId(skuId);
            Integer count = item.getCount();
            hasStock.setNum(count);
            //查询这个商品的所有仓库
            List<Long> wareIds = this.baseMapper.selectWareHasStock(skuId);
            hasStock.setWareId(wareIds);
            return hasStock;
        }).collect(Collectors.toList());

        //锁定库存
        Boolean b = true;
        for (SkuWareHasStock stock : collect) {
            Boolean skuStock = false; //该商品仓库默认为没有货
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            Integer num = stock.getNum();
            //遍历仓库
            for (Long wareId : wareIds) {
                //更新仓库信息
                int count = this.baseMapper.updateWareStock(skuId,num,wareId);
                if (count==1){
                    //成功 有货则返回
                    skuStock = true;
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
                    detailEntity.setSkuId(skuId);
                    detailEntity.setTaskId(taskEntity.getId());
                    detailEntity.setLockStatus(1);
                    detailEntity.setSkuNum(stock.getNum());
                    //锁库存
                    orderTaskDetailService.save(detailEntity);
                    //发送消息
                    int i = 1/0;
                    StockDeailTo stockDeailTo = new StockDeailTo();
                    BeanUtils.copyProperties(detailEntity,stockDeailTo);
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(taskEntity.getId());
                    stockLockedTo.setStockDeailTo(stockDeailTo);
                    //stock-delay-stock->stock-release-stock
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                    break;
                }
            }
            if (skuStock==false){
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Override
    public void unLockStock(StockLockedTo to) {
        //获取订单项信息
        StockDeailTo stockDeailTo = to.getStockDeailTo();
        Long id = stockDeailTo.getId();
        //根据id获取工作单项信息
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(id);
        if (byId!=null){
            //库存锁定成功
            //获取id
            Long toId = to.getId();
            //获取订单编号
            WareOrderTaskEntity taskServiceById = orderTaskService.getById(toId);
            String orderSn = taskServiceById.getOrderSn();
            //根据订单编号获取订单信息
            R byOrderSn = orderFeign.getByOrderSn(orderSn);
            if (byOrderSn.getcode()==0){
                //远程调用成功
                OrderEntityVo data = byOrderSn.getData(new TypeReference<OrderEntityVo>() {
                });
                if (data==null || data.getStatus()==4){
                    //如果订单已锁定
                    if (byId.getLockStatus()==1){
                        //解锁库存
                        unStockLock(stockDeailTo.getSkuId(),stockDeailTo.getWareId(),stockDeailTo.getSkuNum(),id);
                    }
                }
            }
        }else {
            //失败
            throw new RuntimeException("远程服务调用失败");
        }
    }

    /**
     * 修改订单状态后发送消息给库存
     * @param orderTo
     */
    @Override
    public void OrderWareClose(OrderTo orderTo) {
        //根据订单编号查询工作单
       WareOrderTaskEntity entity =  orderTaskService.selectOrderSn(orderTo.getOrderSn());
       //根据工作单id查询工作单详情信息
        List<WareOrderTaskDetailEntity> taskDetailEntities = orderTaskDetailService.getTaskId(entity.getId());
        //遍历这个工作单详情
        for (WareOrderTaskDetailEntity taskDetailEntity : taskDetailEntities) {
            if (taskDetailEntity.getLockStatus() == 1) {
                //解锁库存 Long skuId, Long wareId, Integer skuNum,Long id
                unStockLock(taskDetailEntity.getSkuId(),taskDetailEntity.getWareId(),taskDetailEntity.getSkuNum(),entity.getId());
            }
        }

    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId; //仓库id
    }
}